import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Modal,
  Image,
  TouchableWithoutFeedback,
  ScrollView,
  Alert,
  StatusBar,
  TextInput,
  Dimensions,
} from "react-native";
import React, { useState, useEffect, useRef, useContext } from "react";
import GoodsContext from "../../context/suppiler/goodsContext";
import ComMaterialContext from "../../context/suppiler/comMaterialContext";
import * as ImagePicker from "expo-image-picker";
import ScrollPicker from "../../components/ScrollPicker";

const width = Dimensions.get("window").width;

const SuppilerAdd = ({ navigation, route }) => {
  const { type, itemDetail } = route.params;

  const { addGoods, editGoods } = useContext(GoodsContext);
  const { companyMaterial } = useContext(ComMaterialContext);

  const calType = ["按面积", "按重量"];
  const shapes = ["圆形", "长方形"];

  let categories = []; //公司所购材料种类
  let count;
  for (let i = 0; i < companyMaterial.length; i++) {
    count = 0;
    for (let j = 0; j < categories.length; j++) {
      if (categories[j] === companyMaterial[i].category) {
        count++;
        break;
      }
    }
    if (count == 0) {
      categories[categories.length] = companyMaterial[i].category;
    }
  }

  let result = [];
  for (let j = 0; j < categories.length; j++) {
    let detail = [];
    for (let i = 0; i < companyMaterial.length; i++) {
      if (companyMaterial[i].category === categories[j]) {
        detail.push({
          type: companyMaterial[i].type,
          density: companyMaterial[i].density,
          _id: companyMaterial[i]._id,
          m_cost: companyMaterial[i].m_cost,
          processMode: companyMaterial[i].processMode,
        });
      }
    }

    result.push({
      category: categories[j],
      types: detail,
    });
  }

  const AllTypes = [];
  categories.map((item, index) => {
    let t_material = result[index].types.map((item) => {
      return item.type;
    });
    t_material.unshift("");
    t_material.push("");
    AllTypes.push(t_material);
  });
  categories.unshift("");
  categories.push("");

  let baseCategoryId = 0;
  let baseTypeId = 0;
  let basecost = "";
  let baseprocess = 0;
  let shroudCategoryId = 0;
  let shroudTypeId = 0;
  let shroudcost = "";
  let shroudprocess = 0;
  let shap = 0;
  let title = "";
  let auto = false;
  let originImages = [];

  if (itemDetail !== undefined) {
    // console.log("待修改商品", itemDetail);
    baseCategoryId = (result || []).findIndex(
      (i) => i.category === itemDetail.baseplate.category
    );
    shroudCategoryId = (result || []).findIndex(
      (i) => i.category === itemDetail.shroudplate.category
    );
    const baseType = result[baseCategoryId].types.map((item) => {
      return item.type;
    });
    const shroudType = result[shroudCategoryId].types.map((item) => {
      return item.type;
    });
    baseTypeId = (baseType || []).findIndex(
      (i) => i === itemDetail.baseplate.type
    );

    shroudTypeId = (shroudType || []).findIndex(
      (i) => i === itemDetail.shroudplate.type
    );

    basecost = itemDetail.b_process.price.toString();
    baseprocess = Number(itemDetail.b_process.processMode);
    shroudcost = itemDetail.s_process.price.toString();
    shroudprocess = Number(itemDetail.s_process.processMode);
    shap = (shapes || []).findIndex((i) => i === itemDetail.shape);
    title = itemDetail.title;
    auto = false;
    originImages = itemDetail.image;

    // console.log("baseCategoryId", baseCategoryId);
    // console.log("baseTypeId", baseTypeId);
    // console.log("baseType", baseType);
    // console.log("basecost", basecost);
    // console.log("baseprocess", baseprocess);
    // console.log("shroudCategoryId", shroudCategoryId);
    // console.log("shroudTypeId", shroudTypeId);
    // console.log("shroudcost", shroudcost);
    // console.log(" shroudprocess", shroudprocess);
    // console.log("shap", shap);
    // console.log("title", title);
  }
  const [isVisible, setIsVisible] = useState(false);
  const [imageList, setImageList] = useState([]); //新增图片
  const [originImage, setOriginImage] = useState(originImages); //原始需保留图片
  const [deleteOriImage, setDeleteOriImage] = useState([]); //原始需删除图片

  const [baseCategory, setBaseCategory] = useState(baseCategoryId); //类别
  const [basePlate, setBasePlate] = useState(baseTypeId); //型号
  const [baseProcess, setBaseProcess] = useState(basecost); //加工费
  const [baseSelected, setBaseSelected] = useState(baseprocess); //0表示按面积，1表示按体积（加工方式）

  const [shroudCategory, setShroudCategory] = useState(shroudCategoryId); //类别
  const [shroudPlate, setShroudPlate] = useState(shroudTypeId); //型号
  const [shroudProcess, setShroudProcess] = useState(shroudcost); //加工费
  const [shroudSelected, setShroudSelected] = useState(shroudprocess); //0表示按面积，1表示按体积（加工方式）

  const [shape, setShape] = useState(shap);

  // const types = ["钢板QF987", "铜板QF87", "锌板F98"];

  const [name, setName] = useState(title);
  const [autoName, setAutoName] = useState(auto);

  const [isConfirm, setIsConfirm] = useState(false);

  let realBase = useRef();
  realBase.current = basePlate;

  let realShroud = useRef();
  realShroud.current = shroudPlate;

  let realBaseCategory = useRef();
  realBaseCategory.current = baseCategory;

  let realShroudCategory = useRef();
  realShroudCategory.current = shroudCategory;

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      // aspect: [1, 1],
      quality: 1,
    });
    if (!result.cancelled) {
      setImageList([...imageList, result]);
      setIsVisible(false);
    }
    // console.log(result);
  };

  const openCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setImageList([...imageList, result]);
      setIsVisible(false);
    }
  };

  const deleteImage = (url) => {
    Alert.alert("提示", "要删除这张照片吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          // console.log("要删除的项是", id);
          let images = imageList.filter((item) => item.uri !== url);
          setImageList(images);
        },
      },
    ]);
  };

  const deleteOriginImage = (image) => {
    Alert.alert("提示", "要删除这张照片吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          // console.log("要删除的项是", id);
          // let images = originImage.filter((item) => item._id !== image._id);
          let images = originImage.filter((item) => image != item);
          setOriginImage(images);
          setDeleteOriImage([...deleteOriImage, image]);
        },
      },
    ]);
  };

  const confirmAdd = () => {
    Alert.alert("提示", "确定要提交吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: async () => {
          if (type === "add") {
            if (baseProcess == "" || baseProcess == 0) {
              Alert.alert("提示", "基板加工费不能为空", [{ text: "确定" }]);
              return;
            }
            if (shroudProcess == "" || shroudProcess == 0) {
              Alert.alert("提示", "覆板加工费不能为空", [{ text: "确定" }]);
              return;
            }
            if (name == "") {
              Alert.alert("提示", "商品名称不能为空", [{ text: "确定" }]);
              return;
            }
            // if (imageList.length == 0) {
            //   Alert.alert("提示", "请添加至少一张图片", [{ text: "确定" }]);
            //   return;
            // }
            // if (imageList.length > 6) {
            //   Alert.alert("提示", "最多只能添加6张图片", [{ text: "确定" }]);
            //   return;
            // }
            setIsConfirm(true);
            let item = {
              shape: shapes[shape],
              baseplate: result[baseCategory].types[basePlate]._id,
              b_process: {
                price: Number(baseProcess),
                processMode: baseSelected,
              },
              shroudplate: result[shroudCategory].types[shroudPlate]._id,
              s_process: {
                price: Number(shroudProcess),
                processMode: shroudSelected,
              },
              // image: imageList,
              title: name,
            };
            // console.log("添加商品", item);
            addGoods(
              item,
              () => {
                navigation.navigate("SupplierHome");
              },
              () => {
                setIsConfirm(false);
              }
            );
          } else {
            if (baseProcess == "" || baseProcess == 0) {
              Alert.alert("提示", "基板加工费不能为空", [{ text: "确定" }]);
              return;
            }
            if (shroudProcess == "" || shroudProcess == 0) {
              Alert.alert("提示", "覆板加工费不能为空", [{ text: "确定" }]);
              return;
            }
            if (name == "") {
              Alert.alert("提示", "商品名称不能为空", [{ text: "确定" }]);
              return;
            }
            // if (imageList.length == 0 && originImage.length == 0) {
            //   Alert.alert("提示", "请添加至少一张图片", [{ text: "确定" }]);
            //   return;
            // }
            // if (imageList.length + originImage.length > 6) {
            //   Alert.alert("提示", "最多只能添加6张图片", [{ text: "确定" }]);
            //   return;
            // }
            setIsConfirm(true);
            let item = {
              _id: itemDetail._id,
              shape: shapes[shape],
              baseplate: {
                _id: result[baseCategory].types[basePlate]._id,
                category: result[baseCategory].category,
                type: result[baseCategory].types[basePlate].type,
                density: result[baseCategory].types[basePlate].density,
                m_cost: result[baseCategory].types[basePlate].m_cost,
                processMode: result[baseCategory].types[basePlate].processMode,
              },
              b_process: {
                price: Number(baseProcess),
                processMode: baseSelected,
              },
              shroudplate: {
                _id: result[shroudCategory].types[shroudPlate]._id,
                category: result[shroudCategory].category,
                type: result[shroudCategory].types[shroudPlate].type,
                density: result[shroudCategory].types[shroudPlate].density,
                m_cost: result[shroudCategory].types[shroudPlate].m_cost,
                processMode:
                  result[shroudCategory].types[shroudPlate].processMode,
              },
              s_process: {
                price: Number(shroudProcess),
                processMode: shroudSelected,
              },

              title: name,
              image: imageList,
            };

            editGoods(
              item,
              originImage,
              deleteOriImage,
              (tag) => {
                navigation.navigate("SupplierHome");
              },
              () => {
                setIsConfirm(false);
              }
            );
          }
        },
      },
    ]);
  };
  return (
    <View style={styles.container}>
      <View
        style={{
          alignItems: "center",
        }}
      >
        {/* <View style={styles.titleView}>
          <View style={{ width: "10%" }}>
            <Ionicons name="ios-time-outline" size={22} color="#fff" />
          </View>
          <View
            style={{
              width: "80%",
              alignItems: "center",
            }}
          >
            <Text style={styles.titleText}>{添加商品}</Text>
          </View>
          <View style={{ width: "10%" }}>
            <AntDesign name="bars" size={22} color="#fff" />
          </View>
        </View> */}
        <ScrollView
          style={styles.scrollViewStyle}
          vertical={true} // 垂直方向
        >
          <View
            style={{
              paddingBottom: 250,
            }}
          >
            <View style={styles.boxView}>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>基板：</Text>
                </View>
                <View style={styles.inputView}>
                  <ScrollPicker
                    options={[categories, AllTypes]}
                    selectedIndex={[baseCategory, basePlate]}
                    onSubmit={(index1, category, index2, type) => {
                      setBaseCategory(index1);
                      realBaseCategory.current = index1;
                      setBasePlate(index2);
                      realBase.current = index2;
                      if (autoName) {
                        let title =
                          categories[realBaseCategory.current] +
                          result[realBaseCategory.current].types[
                            realBase.current
                          ].type +
                          "*" +
                          categories[realShroudCategory.current] +
                          result[realShroudCategory.current].types[
                            realShroud.current
                          ].type;
                        setName(title);
                      }
                    }}
                  ></ScrollPicker>
                </View>
              </View>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>加工方式：</Text>
                </View>
                <View style={{ flexDirection: "row", flexWrap: "wrap" }}>
                  {calType.map((tag, index) => {
                    return (
                      <TouchableOpacity
                        key={index}
                        onPress={() => {
                          setBaseSelected(index);
                        }}
                      >
                        <View
                          style={
                            index === baseSelected
                              ? styles.optionsSelected
                              : styles.optionsView
                          }
                        >
                          <Text
                            style={
                              index === baseSelected
                                ? styles.textSelected
                                : styles.optionsText
                            }
                          >
                            {tag}
                          </Text>
                        </View>
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>加工费：</Text>
                </View>
                <View style={[styles.inputView, { width: "79%" }]}>
                  <TextInput
                    value={baseProcess}
                    keyboardType="numeric"
                    onChangeText={(cost) => setBaseProcess(cost)}
                    placeholder="请输入基板加工费"
                    textAlign="center"
                    style={{ marginLeft: 20, height: 27, width: 190 }}
                  />
                  {baseSelected === 0 ? (
                    <Text style={{ fontSize: 13 }}>元/㎡</Text>
                  ) : (
                    <Text style={{ fontSize: 13 }}>元/kg</Text>
                  )}
                </View>
              </View>
            </View>

            <View style={styles.boxView}>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>覆板：</Text>
                </View>
                <View style={styles.inputView}>
                  <ScrollPicker
                    options={[categories, AllTypes]}
                    selectedIndex={[shroudCategory, shroudPlate]}
                    onSubmit={(index1, category, index2, type) => {
                      setShroudCategory(index1);
                      setShroudPlate(index2);
                      realShroudCategory.current = index1;
                      realShroud.current = index2;
                      if (autoName) {
                        let title =
                          categories[realBaseCategory.current + 1] +
                          result[realBaseCategory.current].types[
                            realBase.current
                          ].type +
                          "*" +
                          categories[realShroudCategory.current + 1] +
                          result[realShroudCategory.current].types[
                            realShroud.current
                          ].type;
                        setName(title);
                      }
                    }}
                  ></ScrollPicker>
                </View>
              </View>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>加工方式：</Text>
                </View>
                <View style={{ flexDirection: "row", flexWrap: "wrap" }}>
                  {calType.map((tag, index) => {
                    return (
                      <TouchableOpacity
                        key={index}
                        onPress={() => {
                          setShroudSelected(index);
                        }}
                      >
                        <View
                          style={
                            index === shroudSelected
                              ? styles.optionsSelected
                              : styles.optionsView
                          }
                        >
                          <Text
                            style={
                              index === shroudSelected
                                ? styles.textSelected
                                : styles.optionsText
                            }
                          >
                            {tag}
                          </Text>
                        </View>
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>加工费：</Text>
                </View>
                <View style={[styles.inputView, { width: "79%" }]}>
                  <TextInput
                    value={shroudProcess}
                    keyboardType="numeric"
                    onChangeText={(cost) => setShroudProcess(cost)}
                    placeholder="请输入覆板加工费"
                    textAlign="center"
                    style={{ marginLeft: 20, height: 27, width: 190 }}
                  />
                  {shroudSelected === 0 ? (
                    <Text style={{ fontSize: 13 }}>元/㎡</Text>
                  ) : (
                    <Text style={{ fontSize: 13 }}>元/kg</Text>
                  )}
                </View>
              </View>
            </View>

            <View style={styles.boxView}>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>商品名称：</Text>
                </View>
                <View style={[styles.inputView, { width: "75%" }]}>
                  <TextInput
                    value={name}
                    onChangeText={(name) => setName(name)}
                    placeholder="请输入商品名称"
                    textAlign="center"
                    style={{ marginLeft: 20, height: 27, width: 133 }}
                  />
                  <TouchableOpacity
                    onPress={() => {
                      console.log(
                        "类型---",
                        categories[realBaseCategory.current + 1]
                      );
                      setAutoName(!autoName);
                      let title;
                      if (!autoName) {
                        title =
                          categories[realBaseCategory.current + 1] +
                          result[realBaseCategory.current].types[
                            realBase.current
                          ].type +
                          "*" +
                          categories[realShroudCategory.current + 1] +
                          result[realShroudCategory.current].types[
                            realShroud.current
                          ].type;
                      } else {
                        title = "";
                      }
                      setName(title);
                    }}
                  >
                    <View
                      style={[
                        autoName ? styles.optionsSelected : styles.optionsView,
                        { marginRight: 0 },
                      ]}
                    >
                      <Text
                        style={[
                          autoName ? styles.textSelected : styles.optionsText,
                          { marginRight: 0 },
                        ]}
                      >
                        自动生成
                      </Text>
                    </View>
                  </TouchableOpacity>
                </View>
              </View>
              <View style={styles.boxItem}>
                <View style={styles.itemTitle}>
                  <Text>形状：</Text>
                </View>
                <View
                  style={{
                    flexDirection: "row",
                    flexWrap: "wrap",
                  }}
                >
                  {shapes.map((tag, index) => {
                    return (
                      <TouchableOpacity
                        key={index}
                        onPress={() => {
                          setShape(index);
                        }}
                      >
                        <View
                          style={
                            index == shape
                              ? styles.optionsSelected
                              : styles.optionsView
                          }
                        >
                          <Text
                            style={
                              index == shape
                                ? styles.textSelected
                                : styles.optionsText
                            }
                          >
                            {tag}
                          </Text>
                        </View>
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
            </View>

            <View style={styles.boxView}>
              <TouchableOpacity onPress={() => confirmAdd()}>
                <View style={styles.btnView}>
                  <Text style={{ color: "#fff" }}>提交</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "#eee",
  },
  titleView: {
    alignItems: "center",
    // justifyContent: "center",
    backgroundColor: "#51bfe5",
    width: width,
    height: 60,
    paddingLeft: 10,
    flexDirection: "row",
  },
  titleText: {
    fontSize: 16,
    fontWeight: "bold",
    color: "#fff",
  },
  scrollViewStyle: {
    backgroundColor: "#eeeeee",
  },
  boxView: {
    backgroundColor: "#fcfcfc",
    marginTop: 10,
    width: width,
    paddingLeft: 15,
    paddingRight: 15,
    paddingTop: 7,
    paddingBottom: 7,
  },
  boxItem: {
    flexDirection: "row",
    padding: 5,
    // flexWrap: "wrap",
  },
  itemTitle: {
    marginTop: 7,
  },
  optionsView: {
    borderRadius: 5,
    marginTop: 5,
    padding: 4,
    paddingLeft: 10,
    paddingRight: 10,
    // backgroundColor: "#51bfe5",
    backgroundColor: "#fff",
    marginRight: 10,
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.5, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
  },
  optionsSelected: {
    borderRadius: 5,
    marginTop: 5,
    padding: 4,
    paddingLeft: 10,
    paddingRight: 10,
    marginRight: 10,
    backgroundColor: "#51bfe5",
  },
  optionsText: {
    color: "#000",
  },
  textSelected: {
    color: "#fff",
  },
  btnView: {
    marginTop: 10,
    marginBottom: 10,
    width: "100%",
    height: 30,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 3,
    // 浅色
    backgroundColor: "#51bfe5",
  },
  inputView: {
    justifyContent: "center",
    width: "83%",
    borderColor: "#51bfe5",
    borderBottomWidth: 1,
    flexDirection: "row",
    alignItems: "center",
    paddingRight: 10,
  },
});

export default SuppilerAdd;
